<script setup>
import ChannelSelect from '@/components/ChannelSelect.vue'
import { ref } from 'vue'
import {
  articleDetailService,
  articlePublishService,
  articleEditService
} from '@/api/article.js'
import { Plus } from '@element-plus/icons-vue'
import { QuillEditor } from '@vueup/vue-quill'
import '@vueup/vue-quill/dist/vue-quill.snow.css'
import { baseURL } from '@/utils/request.js'
import axios from 'axios'

const drawerOpen = ref(false) // 发布文章的抽屉打开状态

// 默认数据
const defaultForm = {
  title: '',
  cate_id: '',
  cover_img: '',
  content: '',
  state: ''
}

// 准备数据
const formModel = ref({
  ...defaultForm
})

// 表单校验规则
const rules = ref({
  title: [{ required: true, message: '请输入文章标题', trigger: 'blur' }],
  content: [{ required: true, message: '请输入文章内容', trigger: 'blur' }],
  cate_id: [{ required: true, message: '请选择文章分类', trigger: 'blur' }],
  cover_img: [{ required: true, message: '请选择文章封面', trigger: 'blur' }]
})

// 文章封面处理
const imageUrl = ref('')
const onUploadFile = (uploadFile) => {
  imageUrl.value = URL.createObjectURL(uploadFile.raw)
  formModel.value.cover_img = uploadFile.raw
}

const openDrawer = async (row) => {
  drawerOpen.value = true
  // 编辑操作，需要请求文章详情数据
  if (row.id) {
    const result = await articleDetailService(row.id)
    formModel.value = result.data.data
    // 图片回显
    imageUrl.value = baseURL + formModel.value.cover_img
    const file = await imageUrlToFile(imageUrl.value, formModel.value.cover_img)
    formModel.value.cover_img = file
  }
  // 发布文章操作
  else {
    formModel.value = { ...defaultForm }
    imageUrl.value = ''
  }
}

// 将网络地址转换为文件对象
async function imageUrlToFile(imageUrl, filename) {
  try {
    // 使用axios 请求图片
    const response = await axios.get(imageUrl, {
      responseType: 'arraybuffer'
    })
    // 转换为 blob 对象
    const blob = new Blob([response.data], {
      type: response.headers['content-type']
    })
    // 创建一个File对象
    const file = new File([blob], filename, {
      type: response.headers['content-type']
    })
    return file
  } catch (error) {
    console.error('Error converting image URL to file:', error)
    return null
  }
}

// 文章发布与编辑操作
const quillEditorRef = ref()
const emit = defineEmits(['success'])
const onPublish = async (state) => {
  formModel.value.state = state
  const formData = new FormData()
  // 转换为 formData 对象
  for (const key in formModel.value) {
    formData.append(key, formModel.value[key])
  }
  if (formModel.value.id) {
    const result = await articleEditService(formData)
    ElMessage.success(result.data.message)
    emit('success', 'modify')
    drawerOpen.value = false
  } else {
    const result = await articlePublishService(formData)
    quillEditorRef.value.setHTML('')
    ElMessage.success(result.data.message)
    emit('success', 'add')
    drawerOpen.value = false
  }
}

defineExpose({
  openDrawer
})
</script>

<template>
  <el-drawer title="文章发布" direction="rtl" size="40%" v-model="drawerOpen">
    <el-form :model="formModel" :rules="rules">
      <el-form-item label="文章标题：" prop="title">
        <el-input v-model="formModel.title"></el-input>
      </el-form-item>
      <el-form-item label="文章分类：" prop="cate_id">
        <ChannelSelect width="100%" v-model="formModel.cate_id"></ChannelSelect>
      </el-form-item>
      <el-form-item label="文章封面：" prop="cover_img">
        <el-upload
          class="avatar-uploader"
          :auto-upload="false"
          :show-file-list="false"
          :on-change="onUploadFile"
          v-model="formModel.cover_img"
        >
          <img v-if="imageUrl" :src="imageUrl" class="avatar" alt="图片" />
          <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
        </el-upload>
      </el-form-item>
      <el-form-item label="文章内容：" prop="content">
        <div class="editor" style="width: 100%">
          <QuillEditor
            theme="snow"
            content-type="html"
            v-model:content="formModel.content"
            style="min-height: 350px"
            v-model="formModel.content"
            ref="quillEditorRef"
          ></QuillEditor>
        </div>
      </el-form-item>
      <el-form-item> </el-form-item>
    </el-form>
    <div style="display: flex; justify-content: flex-end; margin-top: 30px">
      <el-button @click="onPublish('草稿')" type="info">存为草稿</el-button>
      <el-button @click="onPublish('已发布')" type="primary"
        >立即发布</el-button
      >
    </div>
  </el-drawer>
</template>

<style lang="scss" scoped>
.avatar-uploader {
  :deep() {
    .avatar {
      width: 178px;
      height: 178px;
      display: block;
    }
    .el-upload {
      border: 1px dashed var(--el-border-color);
      border-radius: 6px;
      cursor: pointer;
      position: relative;
      overflow: hidden;
      transition: var(--el-transition-duration-fast);
    }
    .el-upload:hover {
      border-color: var(--el-color-primary);
    }
    .el-icon.avatar-uploader-icon {
      font-size: 28px;
      color: #8c939d;
      width: 178px;
      height: 178px;
      text-align: center;
    }
  }
}
</style>
